package com.huika.renrench.control.my.activity;

import java.text.DecimalFormat;

import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.google.gson.reflect.TypeToken;
import com.huika.lib.utils.MoneyShowTool;
import com.huika.renrench.GlobalApp;
import com.huika.renrench.R;
import com.huika.renrench.config.UrlConstants;
import com.huika.renrench.control.common.activity.AucceedActivity;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.control.my.activity.WithDrawActivity.MyWatcher;
import com.huika.renrench.http.FormResultRequest;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.view.TitleBarHelper;

/**
 * @author yangyuan
 * @date：2015年6月3日
 * @describe:债权转让
 */
public class MakeOverActivity extends BaseAct{
	
	public final static String CANINVESTAMOUNT = "CaninvestAmount";
	public final static String INVESTAMOUNT = "InvestAmount";
	public final static String MESSAGESTR = "MessageStr";
	public final static String AMOUNTM3 = "amountM3";
	public final static String AMOUNTM2 = "amountM2";
	public final static String RATE2 = "rate2";
	public final static String RATE3 = "rate3";
	

	private TextView text_transferable;//在投总金额
	private TextView text_caninvest_amount;//可转让金额
	private EditText edit_make_over;//转让金额
	private TextView text_cost;//转让费用
	private TextView text_can_free_transfer_amount;//免费转让金额
	
	private Button button_confirm;
	private TextView text_hint;
	
	private String InvestAmount = "";
	private String CaninvestAmount = "";
	private double InvestAmountDouble = 0;
	private double CaninvestAmountDouble = 0;
	private double overDouble = 0;
	private String MessageStr = "";
	private double amountM3;
	private double amountM2;
	private double rate2;
	private double rate3;
	
	
	@Override
	public void setRootView() {
		setContentView(R.layout.make_over_activity);
	}
	
	@Override
	protected void initWidget() {
		super.initWidget();
		new TitleBarHelper(this, R.string.left_back, -1, R.string.make_over);
		
		text_transferable = (TextView) findViewById(R.id.text_transferable);
		text_caninvest_amount = (TextView) findViewById(R.id.text_caninvest_amount);
		edit_make_over = (EditText) findViewById(R.id.edit_make_over);
		text_cost = (TextView) findViewById(R.id.text_cost);
		button_confirm = (Button) findViewById(R.id.button_confirm);
		text_hint = (TextView) findViewById(R.id.text_hint);
		text_can_free_transfer_amount = (TextView) findViewById(R.id.text_can_free_transfer_amount);
		
		initDataMy();
		setOclicklisen();
	}
	
	private double getPoundage(double inputMoney) {
		if(inputMoney - amountM3 >= 0) {
			return ((amountM3 * rate3) + ((inputMoney - amountM3) * rate2));
		} else {
			return inputMoney * rate3;
		}
	}
	
	protected void initDataMy() {
		super.initData();
		edit_make_over.addTextChangedListener(new MyWatcher());
		
		InvestAmount = getIntent().getExtras().getString(INVESTAMOUNT);
		CaninvestAmount = getIntent().getExtras().getString(CANINVESTAMOUNT);
		MessageStr = getIntent().getExtras().getString(MESSAGESTR);
		amountM3 = getIntent().getExtras().getDouble(AMOUNTM3);
		amountM2 = getIntent().getExtras().getDouble(AMOUNTM2);
		rate2 = getIntent().getExtras().getDouble(RATE2);
		rate3 = getIntent().getExtras().getDouble(RATE3);
		
		try {
			InvestAmountDouble = Double.parseDouble(InvestAmount);
		} catch (Exception e) {
		}
		text_transferable.setText(MoneyShowTool.twolastDFStr(InvestAmount)+"元");
		
		try {
			CaninvestAmountDouble = Double.parseDouble(CaninvestAmount);
		} catch (Exception e) {
		}
		text_caninvest_amount.setText(MoneyShowTool.twolastDFStr(CaninvestAmount)+"元");
		if(rate3 == 0.00d) {
			text_can_free_transfer_amount.setText(MoneyShowTool.twolastDF(amountM3) + "元");
		} else {
			text_can_free_transfer_amount.setText("0.00元");
		}
		Spanned ss = Html.fromHtml(MessageStr);
		text_hint.setText(ss);
	}
	
	private void setOclicklisen() {
		button_confirm.setOnClickListener(this);
	}
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.button_confirm:
			if (CaninvestAmountDouble == 0) {
				showToastMsg("可转让金额不足");
				return;
			}
			try {
				overDouble = Double.parseDouble(getInputStr(edit_make_over));
			} catch (Exception e) {
				showToastMsg("金额输入错误");
			}
			if (overDouble > CaninvestAmountDouble) {
				showToastMsg("可转让金额不足");
				return;
			}
			executeMakeOver();
			showLoadingDialog("提交");
			break;
		}
	}
	
	private void executeMakeOver(){
		FormResultRequest<String> request = new FormResultRequest<String>(UrlConstants.ADDTRANSFER, getexecuteMakeOverResp, this, new TypeToken<RequestResult<String>>() {}.getType());
		JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();//
		ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserId());//userId
		ajaxParams.putCommonTypeParam("transferaAmount", MoneyShowTool.twolastDF(overDouble));//userId
		request.setRequestParams(ajaxParams);
		executeRequest(request);
	}
	
	private Listener<RequestResult<String>> getexecuteMakeOverResp=new Listener<RequestResult<String>>() {
		
		@Override
		public void onResponse(RequestResult<String> result) {
			if (result.flag == 1) {
				setView();
			} else {
				showToastMsg(result.msg);
			}
			dismissLoadingDialog();
			if (mOverlayLayout != null)
				hideOverLay();
		}
	};
	
	private void setView(){
		InvestAmountDouble -= overDouble;
		CaninvestAmountDouble -= overDouble;
		text_transferable.setText("" + MoneyShowTool.twolastDF(InvestAmountDouble)+"元");
		text_caninvest_amount.setText("" + MoneyShowTool.twolastDF(CaninvestAmountDouble)+"元");
		edit_make_over.setText("");
		//跳转成功界面
		Bundle bundle  = new Bundle();
		bundle.putString(AucceedActivity.SUCCEEDSTR,"恭喜您，成功转让" + MoneyShowTool.twolastDF(overDouble) +"元！");
		bundle.putInt(AucceedActivity.TITESTR, R.string.succeed_str);
		showActivity(this, AucceedActivity.class,bundle);
		overDouble = 0;
	}
	
	class MyWatcher implements TextWatcher {
		String tempStr;
		
		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			tempStr = s.toString();
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			if(!checkInputMoney(s.toString())) { 
				edit_make_over.setText(tempStr);
				edit_make_over.setSelection(edit_make_over.length());
				return;
			} else if(s.length() > 1 && s.toString().substring(0, 1).equals("0")&&!s.toString().substring(1, 2).equals(".")) {
					edit_make_over.setText(s.toString().substring(1));
					edit_make_over.setSelection(edit_make_over.length());
			}else if (s.length() > 1 && s.toString().substring(0, 1).equals(".")) {
				edit_make_over.setText("0"+s.toString()+"");
				edit_make_over.setSelection(edit_make_over.length());
			} else if(!s.toString().endsWith(".") && !s.toString().equals("")) {
				text_cost.setText(MoneyShowTool.twolastDF(getPoundage(Double.parseDouble(s.toString())), false) + "元");
			} else if(s.toString().equals("")) {
				text_cost.setText("0.00元");
			}
		}
		
	}
	
	private boolean checkInputMoney(String money) {
		String patten = "^[0-9]{0,15}+(([.]{1})+([0-9]{0,2}))?$";
		return money.equals("")?true:money.matches(patten);
	}

}
